<template>
  <div style="display: flex; align-items: baseline">
    <el-upload
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      class="avatar-uploader"
      action="#"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-button style="margin-left: 20px;position: relative;top: -10px;" type="danger" icon="el-icon-delete" circle @click="del()" />
  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: auto;
  display: block;
}
</style>

<script>
import axios from 'axios'
export default {
  props:['imgsrc']
  ,
  watch:{
    imgsrc(item){
      this.imageUrl=item
    }
    ,
    deep:true

  }
  ,
  data() {
    return {
      imageUrl: '',
      imageId: ''
    }
  },
  created() {

    if (this.imgsrc){
      this.imageUrl=this.imgsrc
    }

    // this.imageUrl = this.$attrs.imageurl
    // this.imageId = this.$attrs.imageId
  },
  methods: {
    del() {
      this.imageUrl = ''


      this.$emit('url', '')
    },

    handleAvatarSuccess(res, file) {
      console.log(res)
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const loading = this.$loading({
        lock: true,
        text: '图片上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      const that = this
      var formData = new FormData()
      formData.append('file', file)
      formData.append('id', this.imageId || parseInt(new Date().getTime() / 1000))
      // 上传图片地址
      const url = process.env.VUE_APP_BASE_API + '/upload'

      axios.post(url, formData).then(res => {
        loading.close()
        const url = res.data.file
        that.$emit('url', url)
      })
      return false
    }
  }
}
</script>
